;
(function (window, angular) {
	'use strict';
	angular.module("Controller.Corruption.PriceWarning", [])
		.controller("PriceWarningCtrl", ["$scope", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "UserContextService", "EventBus","$stateParams", function ($scope, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, UserContextService, EventBus,$stateParams) {
			$scope.handleMultiInput = function (e) {
				$scope.condition.materialsNos = UserContextService.MultiInput(e.target.value);
			};

			$scope.markInfo = {
				allChecked: false,
				curRow: -1
			};
			$scope.pageInfo = {
				totalPages: 1,
				totalRows: 0,
				pageSize: 10,
				curPage: 1
			};
			$scope.toolbarConfig = {
				showColConfig: false
			};


			$scope.condition = {};
			$scope.dataList = [];
			$scope.tableConfig = {
				fixedWidth: 100,
				scrollWidth: 1800,
				tableCol: [
					{
						name: "零件编号",
						dataField: "materialsNo",
						width: 120,
						isShow: true,
						isFixed: false,
					},
					{
						name: "零件中文名",
						dataField: "materialsDes",
						width: 120,
						isShow: true,
						isFixed: false,
					},
					{
						name: "零件分类",
						dataField: "materialsType",
						width: 120,
						isShow: true,
						isFixed: false,
					},
					{
						name: "原基准价",
						dataField: "oldPrice",
						width: 120,
						isShow: true,
						isFixed: false,
					},
					{
						name: "现基准价",
						dataField: "price",
						width: 120,
						isShow: true,
						isFixed: false,
					},
					{
						name: "升降状态",
						dataField: "jackConShow",
						width: 120,
						isShow: true,
						isFixed: false,
					},
					{
						name: "小于下限",
						dataField: "lessThanMin",
						width: 120,
						isShow: true,
						isFixed: false,
					},
					{
						name: "大于上限",
						dataField: "moreThanMax",
						width: 120,
						isShow: true,
						isFixed: false,
					},
					{
						name: "异常原因",
						dataField: "changeReason",
						width: 140,
						isShow: true,
						isFixed: false,
					},
					{
						name: "价格变动编号",
						dataField: "changeNo",
						width: 140,
						isShow: true,
						isFixed: false,
					},
					{
						name: "调整时间",
						dataField: "adjustDateShow",
						width: 140,
						isShow: true,
						isFixed: false,
					},
					{
						name: "单据状态",
						dataField: "stateShow",
						width: 120,
						isShow: true,
						isFixed: false,
					},
					{
						type: 'operate',
						name: "操作",
						width: 60,
						isShow: true,
						isFixed: true,
					},
				]
			};
			$scope.setFixedWidth = function () {
				$scope.tbStyle = {
					scrollLeft: { left: $scope.tableConfig.fixedWidth + "px" }
				};
			};

			$scope.exportParam = {
				sectionParam: { ids: [] },
				allUrl: ybHttp.RequestUrl("device", "/pricewarn/exportAll")
			};

			$scope.reset = function () {
				$scope.condition = {};
			};

			function getDataList(curPage) {
				$scope.markInfo.allChecked = false;
				$scope.markInfo.curRow = -1;
				$scope.exportParam.sectionParam.ids = [];

				var service = "device";
				var reqUrl = "/pricewarn/list";

				if (!!curPage) {
					$scope.pageInfo.curPage = curPage;
				}
				var param = {
					pageSize: $scope.pageInfo.pageSize,
					pageNum: $scope.pageInfo.curPage,
					filters: angular.copy($scope.condition)
				};
				ybHttp.Post(service, reqUrl, param).then(function (resp) {
					if (resp.code !== 0) {
						ybWidget.ShowMessage(resp, MESG_TYPE.Error);
						return;
					}
					localStorage.removeItem("billNo")
					angular.forEach(resp.value.list, function (item) {
						item.isChecked = false;
						item.adjustDateShow = $filter("YbDate")(item.adjustDate, 'yyyy-MM-dd HH:mm:ss');
						item.jackConShow = $filter("ProgressStatus")(item.jackCon, 'priceChangeState');
						item.stateShow = $filter("ProgressStatus")(item.state, 'priceChangeInstru');
					});
					$scope.pageInfo.totalRows = resp.value.total;
					$scope.pageInfo.totalPages = resp.value.pages;
					$scope.dataList = resp.value.list;
				});
			}


			$scope.switchToolbar = function (toolbar) {
				if (!!$scope.toolbarConfig["show" + toolbar]) {
					$scope.toolbarConfig["show" + toolbar] = false;
				} else {
					$timeout(function () {
						$scope.toolbarConfig["show" + toolbar] = true;
					});
				}
			};

			$scope.selectRow = function (index) {
				$scope.markInfo.curRow = index
			};

			$scope.search = function (curpage) {
				getDataList(curpage);
			};

			function getBillIds() {
				$scope.exportParam.sectionParam.ids = [];
				angular.forEach($scope.dataList, function (item) {
					if (!!item.isChecked) {
						$scope.exportParam.sectionParam.ids.push(item.id);
					}
				});
			}

			$scope.selectAll = function (list, type) {
				for (var i = 0, len = list.length; i < len; i++) {
					list[i].isChecked = angular.isUndefined(type) ? $scope.markInfo.allChecked : $scope.markInfo["allChecked" + type];
				}
				getBillIds();
			};

			function checkAll(list) {
				var selectAll = false;
				for (var i = 0, len = list.length; i < len; i++) {
					if (!list[i].isChecked) {
						selectAll = false;
						break;
					}
					selectAll = true;
				}
				return selectAll;
			}

			$scope.selectSingle = function (item, list, type) {
				var selectAll = false;
				if (!item.isChecked) {
					selectAll = false;
				} else {
					if (!checkAll(list)) {
						selectAll = false;
					} else {
						selectAll = true;
					}
				}
				if (angular.isDefined(type)) {
					$scope.markInfo["allChecked" + type] = selectAll;
				} else {
					$scope.markInfo.allChecked = selectAll;
				}
				getBillIds();
			};

			$scope.addPricewarn = function () {
				const selectedDatas = $scope.dataList.filter(df => df.isChecked);
				if (selectedDatas.length === 0) {
					ybWidget.ShowMessage('请选择需要操作的行');
					return;
				}

				ybWidget.ShowMessage("确定要生成督办单吗？", MESG_TYPE.Ask).then(function () {
					var service = "device";
					var reqUrl = "/pricewarn/addDbd";

					ybHttp.Post(service, reqUrl, selectedDatas.map(s => s.id)).then(function (resp) {
						if (resp.code !== 0) {
							ybWidget.ShowMessage(resp, MESG_TYPE.Error);
							return;
						}
						ybWidget.ShowToaster('success', '操作成功');
					});
				})
			};

			function handleUpdatePricewarn(ids) {
				ybWidget.ShowConfirm("维护价格说明和编号", [{ label: '价格变更编号' }, { label: '异常原因' }]).then(function (data) {
					var service = "device";
					var reqUrl = "/pricewarn/update";

					var param = {
						ids: ids,
						changeNo: data[0].value,
						changeReason: data[1].value,
					};
					ybHttp.Post(service, reqUrl, param).then(function (resp) {
						if (resp.code !== 0) {
							ybWidget.ShowMessage(resp, MESG_TYPE.Error);
							return;
						}
						ybWidget.ShowToaster('success', '操作成功');
						getDataList();
					})
				});
			}

			$scope.updatePricewarnBatch = function () {
				const selectedDatas = $scope.dataList.filter(df => df.isChecked);
				if (selectedDatas.length === 0) {
					ybWidget.ShowMessage('请选择需要操作的行');
					return;
				}
				handleUpdatePricewarn(selectedDatas.map(s => s.id));
			};


			$scope.updatePricewarn = function (item) {
				handleUpdatePricewarn([item.id]);
			};

			$scope.activeFlag = [true, false];
			// 切换标签页
			$scope.changeTab = function (index) {
				$scope.activeFlag = [false, false];
				$scope.activeFlag[index] = true;

				$scope.submitted = false;
			};

			$scope.checkDate = function (obj, startFiled, endFiled) {
				var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
				if (!!timeFormatObj.tStart) {
					obj[startFiled] = timeFormatObj.tStart;
				}
				if (!!timeFormatObj.tEnd) {
					obj[endFiled] = timeFormatObj.tEnd;
				}
			};

			$scope.echartsOption = {
				title: {
					text: '价格变动'
				},
				legend: {
					data: ['价格升高', '价格降低']
				},
				color: ['#ee6666', '#3ba272'],
				xAxis: [
					{
						type: 'category',
						axisLabel: {
							rotate: 45
						},
						data: []
					}
				],
				series: [{ name: '价格升高', type: 'bar' }, { name: '价格降低', type: 'bar' }],
				label: {
					show: true,
					position: 'top',
				},
			};

			$scope.echartsCondition = {};
			$scope.echartsSearch = function (valid) {
				if (!valid) {
					$scope.submitted = true;
					return;
				}

				ybHttp.Post('device', '/priceSchemeWarnRpt/queryPriceRpt', $scope.echartsCondition).then(function (resp) {
					if (resp.code !== 0) {
						ybWidget.ShowMessage(resp, MESG_TYPE.Error);
						return;
					}
					const resT = resp.value || [];
					$scope.echartsOption.xAxis[0].data = resT.map(r => r.day);
					$scope.echartsOption.series[0].data = resT.map(r => r.s);
					$scope.echartsOption.series[1].data = resT.map(r => r.j);
				});
			};

			const obj = { '价格升高': 1, '价格降低': 2 }
			function handleEchartsClick({ seriesName, name }) {
				ybWidget.DataSelector({
					size: 'lg',
					title: `价格变动详情 - ${name} - ${seriesName}`,
					url: '/pricewarn/list',
					otherParams: { jackCon: obj[seriesName], adjustDateStr: name },
					fields: [
						{
							name: '零件编号',
							dataField: 'materialsNo',
							width: "12%"
						},
						{
							name: '零件中文名',
							dataField: 'materialsDes',
							width: "14%"
						},
						{
							name: '原基准价',
							dataField: 'oldPrice',
							width: "12%"
						},
						{
							name: '现基准价',
							dataField: 'price',
							width: "12%"
						},
						{
							name: '小于下限',
							dataField: 'lessThanMin',
							width: "12%"
						},
						{
							name: '大于上限',
							dataField: 'moreThanMax',
							width: "12%"
						},
						{
							name: '异常原因',
							dataField: 'changeReason',
							width: "14%"
						},
						{
							name: '价格变动编号',
							dataField: 'changeNo',
							width: "12%"
						},
					],
					isOnlyShow: true,
				})
			}

			EventBus.Subscribe('onEchartsClick', handleEchartsClick);
			$scope.$on("$destroy", function () {
				EventBus.Unsubscribe("onEchartsClick", handleEchartsClick);
			});


			var btnPermissionCode = {
				priceWarnEdit: window.ActionCode.priceWarnEdit,
				priceWarnAddDbd: window.ActionCode.priceWarnAddDbd,
				priceWarnExport: window.ActionCode.priceWarnExport,
			};
			$scope.btnPermission = {
				priceWarnEdit: true,
				priceWarnAddDbd: true,
				priceWarnExport: true,
			};
			function setBtnPermission() {
				for (var key in btnPermissionCode) {
					$scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
				}
			}

			(function () {
				if ($stateParams.billNo) {
					$scope.condition.id = $stateParams.billNo
					getDataList();
				}else {
					getDataList();
				}
				$scope.setFixedWidth();
				
				UserContextService.SetBtnPermission(setBtnPermission);
			})();
		}])
		;
})(window, window.angular);